package com.infore.qualityControl.util;

import java.beans.BeanInfo;
import java.beans.IntrospectionException;
import java.beans.Introspector;
import java.beans.PropertyDescriptor;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.sql.Timestamp;
import java.text.SimpleDateFormat;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;

import org.springframework.beans.BeanUtils;
import org.springframework.beans.BeanWrapper;
import org.springframework.beans.BeanWrapperImpl;

/**
 * 实体类工具类
 * 
 * @author qiye
 * @date 2018年6月22日 下午1:36:39
 */
public class MyBeanUtils {

	/**
	 * 将空值的属性从目标实体类中复制到源实体类中
	 * 
	 * @param src
	 *            : 要将属性中的空值覆盖的对象(源实体类)
	 * @param target
	 *            :从数据库根据id查询出来的目标对象
	 */
	public static void copyNonNullProperties(Object src, Object target) {
		BeanUtils.copyProperties(src, target, getNullProperties(src));
	}

	/**
	 * 将为空的properties给找出来,然后返回出来
	 * 
	 * @param src
	 * @return
	 */
	public static String[] getNullProperties(Object src) {
		BeanWrapper srcBean = new BeanWrapperImpl(src);
		PropertyDescriptor[] pds = srcBean.getPropertyDescriptors();
		Set<String> emptyName = new HashSet<>();
		for (PropertyDescriptor p : pds) {
			Object srcValue = srcBean.getPropertyValue(p.getName());
			if (srcValue == null || "".equals(srcValue)) {
				emptyName.add(p.getName());
			}
		}
		String[] result = new String[emptyName.size()];
		System.out.println("空字段：" + emptyName);
		return emptyName.toArray(result);
	}

	/** 实体类转成map **/
	@SuppressWarnings({ "rawtypes" })
	public static Map<String, Object> convertBeanToMap(Object bean, String pattern)
			throws IntrospectionException, IllegalAccessException, InvocationTargetException {
		Class type = bean.getClass();
		Map<String, Object> returnMap = new HashMap<String, Object>();
		BeanInfo beanInfo = Introspector.getBeanInfo(type);
		PropertyDescriptor[] propertyDescriptors = beanInfo.getPropertyDescriptors();
		SimpleDateFormat simpleDateFormat = new SimpleDateFormat(pattern);
		for (int i = 0; i < propertyDescriptors.length; i++) {
			PropertyDescriptor descriptor = propertyDescriptors[i];
			String propertyName = descriptor.getName();
			if (!propertyName.equals("class")) {
				Method readMethod = descriptor.getReadMethod();
				Object result = readMethod.invoke(bean, new Object[0]);
				if (result != null) {
					if (result instanceof Timestamp) {
						returnMap.put(propertyName, simpleDateFormat.format(result));
					} else {
						returnMap.put(propertyName, result);
					}
				} else {
					returnMap.put(propertyName, "");
				}
			}
		}
		return returnMap;
	}
}
